<!DOCTYPE html>
<html lang="en">

<head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <meta name="referrer" content="no-referrer" />
      <title>商品列表分页</title>
      <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon">
      <link rel="stylesheet" href="./stylesheets/goodsList_pagination.css">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>

<body>
      <!-- 页面头部 -->
      <div class="header-box">
            <div class="header">
                  <!-- 头部导航 -->
                  <div class="header-nav">
                        <a class="header-logo" href="/">
                              <img src="//static.21cake.com/themes/site/img/logo.png" alt="21cake logo">
                              <!-- <img src="/themes/site/img/logo.png" alt=""> -->
                        </a>
                        <!-- 导航中部 -->
                        <ul class="nav-box">
                              <li><a href="./index.html">首页</a></li>
                              <li><a href="./goodsList_pagination.html" target="_self">蛋糕</a></li>
                              <li><a href="./goodsList_pagination.html" target="_self">面包</a></li>
                              <li><a href="./goodsList_pagination.html" target="_self">冰淇淋</a></li>
                              <li><a href="./goodsList_pagination.html" target="_self">咖啡下午茶</a></li>
                              <li><a href="./goodsList_pagination.html" target="_self">咖啡全国送</a></li>
                              <li><a href="./goodsList_pagination.html" target="_self">企业专区</a></li>
                        </ul>
                        <!-- 导航右侧 -->
                        <ul class="right-city-user">
                              <li class="header-app app-download">
                                    <a>APP下载</a>
                                    <ul class="app-list">
                                          <li>
                                                <img src="https://static.21cake.com/themes/site/img/footer-erweima.png"><a>下载享更多优惠</a>
                                          </li>
                                    </ul>
                              </li>
                              <li class="current-city"><a>北京<i></i></a>
                                    <ul class="current-city-list">
                                          <li><a>上海</a></li>
                                          <li><a>天津</a></li>
                                          <li><a>杭州</a></li>
                                          <li><a>无锡</a></li>
                                          <li><a>苏州</a></li>
                                          <li><a>广州</a></li>
                                          <li><a>深圳</a></li>
                                    </ul>
                              </li>
                              <li class="message-list-header  header-select">
                                    <a href="/message/center.html">消息</a>
                                    <ul>
                                          <li><a href="/message/center.html" target="_blank">通知</a></li>
                                          <li><a href="/message/center.html?#delivery" target="_blank">物流</a></li>
                                    </ul>
                              </li>
                              <li><a href="./login.html">登录</a>/
                                    <a href="./register.html">注册</a>
                              </li>
                              <li class="header-cart">
                                    <a href="./carts.html" id="cart-count-icon">
                                          <i></i>
                                    </a>
                              </li>
                        </ul>
                  </div>
            </div>
      </div>


      <!-- 按钮 -->
      <nav aria-label="Page navigation">
            <ul class="pagination">
                  <li id="prev">
                        <a href="#" aria-label="Previous">
                              <span aria-hidden="true">&laquo;</span>
                        </a>
                  </li>

                  <li id="next">
                        <a href="#" aria-label="Next">
                              <span aria-hidden="true">&raquo;</span>
                        </a>
                  </li>
            </ul>
      </nav>

      <!-- 列表渲染 -->
      <div class="my-container">
            <ul id="goods_list">

            </ul>

      </div>


      <script>
            //记载数据，渲染页面，重新渲染，分页
            //分页
            class Pagination {
                  //init有可能要等待loaddata的数据，也有可能是异步的
                  async init() {
                        //先选择元素
                        this.goodsList = $("#goods_list");
                        this.next = $("#next");
                        this.prev = $("#prev");
                        this.btnList = [];
                        this.url = "./json/cake.json";

                        // 新内容 
                        // 一页显示12个，要算index
                        this.renderNum = 12;
                        // 页码;
                        this.page = 1;
                        //初始化
                        this.page_total = 0;
                        //从这里开始改的

                        //加载数据之后得到的结果
                        this.res = await this.loadData();


                        this.render();
                        //渲染按钮
                        this.renderPageBtn();

                        this.bindEvent();
                  }
                  bindEvent() {
                        this.next.addEventListener("click", this.nextPage.bind(this));
                        this.prev.addEventListener("click", this.prevPage.bind(this));
                        //btnList,是中间的那些按钮,index从0开始，页码从1开始
                        this.btnList.forEach((ele, index) => {
                              ele.addEventListener("click", this.toPage.bind(this, index + 1))
                        })
                        this.next.parentNode.addEventListener("click", this.reRender.bind(this))
                  }
                  //加载数据

                  async loadData() {
                        let res = await xhrGet(this.url);
                        res = JSON.parse(res);
                        return res;
                  }

                  //重新渲染
                  reRender() {
                        // 添加对应位置的active;
                        this.btnList.forEach((ele, index) => {
                              if (index + 1 === this.page) {
                                    ele.className = "active";
                              } else {
                                    ele.className = "";
                              }
                        })
                        this.render();
                  }
                  //下一页
                  nextPage() {
                        //若等于了最后一页
                        if (this.page === this.page_total) {
                              return false;
                        } else {
                              this.page++;
                        }
                  }
                  //上一页
                  prevPage() {
                        if (this.page === 1) {
                              return false;
                        } else {
                              this.page--;
                        }
                  }
                  //某一页
                  toPage(index) {
                        this.page = index;
                  }
                  //渲染按钮
                  renderPageBtn() {
                        this.page_total = Math.ceil(this.res.goods_list.length / this.renderNum);
                        //
                        let btnWrap = document.createDocumentFragment();
                        for (var i = 1; i <= this.page_total; i++) {
                              let li = document.createElement("li");
                              let a = document.createElement("a");
                              a.innerHTML = i;
                              li.appendChild(a);
                              //当前页
                              if (i === this.page) {
                                    li.className = "active";
                              }
                              btnWrap.appendChild(li);
                              this.btnList.push(li);
                        }

                        this.next.parentNode.insertBefore(btnWrap, this.next);


                  }
                  //渲染页面
                  render() {
                        // console.log(this.res);
                        //goods_list是后台得到数据的名
                        let goods_list = this.res.goods_list;
                        let html = "";
                        //或者i < =this.renderNum * this.page -1
                        for (var i = this.renderNum * (this.page - 1); i < this.renderNum * this.page; i++) {
                              //商品数组之中的每一项
                              let item = goods_list[i];
                              //判断到最后了item若没有了
                              if (!item) continue;
                              html += `<li class="goods-item">
                                               <div class="img-box">
                                                   <img class="lazy" src="https://static.21cake.com/themes/site/img/pro-list-empty.jpg"
                                                   data-original="${item.hd_thumb_url}" alt="">
                                                   <p class="title-box">
                                                       <a href="javascript:void(0)">${item.goods_name}</a>
                                                    </p>
                                                    <div class="pricerow">
                                                        <h3>百利甜情人</h3>
                                                        <span>￥298.00/2.0磅</span>
                                                    </div>
                                                    <div class="label-entrance">
                                                      <a href="/gallery/tag/17.html">情侣 &gt;</a>
                                                      <a href="/gallery/tag/31.html">人气 &gt;</a>
                                                      <a href="/gallery/tag/44.html">生日 &gt;</a>
                                                    </div>
                                                    <div class="cart">
                                                    <a href="javascript:void(0);" 
                                                       name="pro-list-addcart_12" 
                                                       class="pro-list-addcart" 
                                                       data-id="12">
                                                       <i></i>加入购物车
                                                    </a>
                                                    </div>

                                               </div>
            
                                           </li>`
                        }
                        //放在页面之中
                        this.goodsList.innerHTML = html;
                  }
            }

            function $(selector) {
                  return document.querySelector(selector);
            }

            var pag = new Pagination();
            pag.init();


            /**
             * @function xhrGet 
             *  
             * 利用xhr发送get请求;
             * 
             * xhrGet(url[,data],callback)  
             * 
             * url : 必选
             * data : 可选  => object 
             * callback : 必选
             * 
             */

            function xhrGet(url, data) {
                  return new Promise((resolve, reject) => {
                        var xhr = new XMLHttpRequest();
                        if (typeof data !== "function" && data instanceof Object) {
                              // 拼接字符串; 
                              var _arr = [];
                              for (var key in data) {
                                    _arr.push(`${key}=${data[key]}`)
                              }
                              var _symbol = /\?/.test(url) ? "&" : "?";
                              url += _symbol + _arr.join("&")
                        }
                        xhr.open("GET", url);
                        xhr.send(null);
                        xhr.onreadystatechange = function () {
                              if (xhr.readyState === 4 && xhr.status === 200)
                                    resolve(xhr.responseText);
                        }
                  })
            }

            //懒加载
            //图片进行懒加载
            var aImages = document.getElementsByClassName("lazy"); //获取需要预加载文档内所有的图片
            //loadImg(aImages);
            // console.log(aImages)
            window.onscroll = function () { //滚动条滚动触发
                  loadImg(aImages);
            };
            //getBoundingClientRect 是图片懒加载的核心
            function loadImg(arr) {
                  for (var i = 0, len = arr.length; i < len; i++) {
                        if (arr[i].getBoundingClientRect().top < document.documentElement.clientHeight && !arr[i].isLoad) {
                              arr[i].isLoad = true; //图片显示标志位
                              //arr[i].style.cssText = "opacity: 0;"; 
                              (function (i) {
                                    setTimeout(function () {
                                          if (arr[i].dataset) { //兼容不支持data的浏览器
                                                aftLoadImg(arr[i], arr[i].dataset.original);
                                          } else {
                                                aftLoadImg(arr[i], arr[i].getAttribute("data-original"));
                                          }
                                          arr[i].style.cssText = "transition: 1s; opacity: 1;" //相当于fadein
                                    }, 500)
                              })(i);
                        }
                  }
            }

            function aftLoadImg(obj, url) {
                  var oImg = new Image();
                  oImg.onload = function () {
                        obj.src = oImg.src; //下载完成后将该图片赋给目标obj目标对象
                  }
                  oImg.src = url; //oImg对象先下载该图像
            }
      </script>

      <!-- <script src="./scripts/libs.js"></script>
       <script src="./scripts/goodsList_pagination.js"></script> -->
</body>

</html>